added SSCLI 1.0
[windows-sources.git] / sdk / samples / all in on code / Visual Studio 2008 / CppInteractiveWindowsService / ThreadPool.h
blob44bc76cf9bfa183e435ceafcf5778ba3cbf9684e
1 /****************************** Module Header ******************************\
2 * Module Name: ThreadPool.h
3 * Project: CppInteractiveWindowsService
4 * Copyright (c) Microsoft Corporation.
5 *
6 * The class was designed by Kenny Kerr. It provides the ability to queue
7 * simple member functions of a class to the Windows thread pool.
8 *
9 * Using the thread pool is simple and feels natural in C++.
11 * class CSampleService
12 * {
13 * public:
15 * void AsyncRun()
16 * {
17 * CThreadPool::QueueUserWorkItem(&Service::Run, this);
18 * }
20 * void Run()
21 * {
22 * // Some lengthy operation
23 * }
24 * };
26 * Kenny Kerr spends most of his time designing and building distributed
27 * applications for the Microsoft Windows platform. He also has a particular
28 * passion for C++ and security programming. Reach Kenny at
29 * http://weblogs.asp.net/kennykerr/ or visit his Web site:
30 * http://www.kennyandkarin.com/Kenny/.
32 * This source is subject to the Microsoft Public License.
33 * See http://www.microsoft.com/opensource/licenses.mspx#Ms-PL.
34 * All other rights reserved.
36 * THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
37 * EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
38 * WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
39 \***************************************************************************/
41 #pragma once
43 #include <memory>
46 class CThreadPool
48 public:
50 template <typename T>
51 static void QueueUserWorkItem(void (T::*function)(void),
52 T *object, ULONG flags = WT_EXECUTELONGFUNCTION)
54 typedef std::pair<void (T::*)(), T *> CallbackType;
55 std::auto_ptr<CallbackType> p(new CallbackType(function, object));
57 if (::QueueUserWorkItem(ThreadProc<T>, p.get(), flags))
59 // The ThreadProc now has the responsibility of deleting the pair.
60 p.release();
62 else
64 throw GetLastError();
68 private:
70 template <typename T>
71 static DWORD WINAPI ThreadProc(PVOID context)
73 typedef std::pair<void (T::*)(), T *> CallbackType;
75 std::auto_ptr<CallbackType> p(static_cast<CallbackType *>(context));
77 (p->second->*p->first)();
78 return 0;